<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./OL_SDK/include-openlayers-local.js"></script>
    <script src="./libs/gaode.js"></script>
</head>

<body>
    <div id="map">
    </div>
    <script>
        var map = new ol.Map({
            target: "map",
            layers: [gaode],
            view: new ol.View({
                projection: 'EPSG:4326',
                center: [114.30, 30.50],
                zoom: 4
            })
        })
        let source = new ol.source.Vector({})
        let layer = new ol.layer.Vector({
            source
        })
        map.addLayer(layer)
        /* 2、创建画笔  */
        let draw = new ol.interaction.Draw({
            // 在哪个画布上绘制
            source: source,
            // 绘制的类型
            type: 'LineString',// 'Circle' 'LineString' 'Point'
            // geometryFunction：Function that is called when 
            // a geometry's coordinates are updated.
            geometryFunction: function (coordinates, geometry) {
                // 在画的过程中实时自动获取coordinates和geometry
                if (!geometry) {
                    //如果没有geometry，就创建一个geometry多边形
                    geometry = new ol.geom.Polygon(null)
                }
                // coordinates会自动获取画线的起点和终点坐标，是一个二维数组
                var start = coordinates[0]
                var end = coordinates[1]
                // 线作为对角线，推出矩形的坐标（此处这个参数也是一个二维数组）
                // console.log([start, [start[0], end[1]], end, [end[0], start[1]], start])
                geometry.setCoordinates([
                    [start, [start[0], end[1]], end, [end[0], start[1]], start],
                ])
                return geometry
            },
            // 在完成多边形环或线串之前可以绘制的点数。默认情况下，没有限制。
            maxPoints: 2
        })
        /* 3、将画笔添加到地图 */
        // console.log(map)
        map.addInteraction(draw);
        /* 监听画笔 */
        draw.on("drawend", evt => {
            var geom = evt.feature.getGeometry()
            console.log(geom, 'geom')
            const coordinates = geom.getCoordinates()
            console.log(coordinates, 'coordinates')// 矩形坐标的三维数组
            // [Array(5)]
            const area = geom.getArea()
            console.log(area)// 面积
        })
    </script>
</body>

</html>